package com.finance.capacity.coefficientTrend.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.capacity.coefficientTrend.request.CoeTrendReq;
import com.finance.capacity.deliveryDetail.bean.pojo.DeliveryDetailList;
import com.finance.capacity.deliveryDetail.capService.IDeliveryDetailService;
import com.finance.capacity.siteCoefficientDaily.bean.pojo.SiteCoeDaily;
import com.finance.capacity.siteCoefficientDaily.bean.pojo.SiteCoeDailyList;
import com.finance.capacity.siteCoefficientDaily.capService.ISiteCoefficientDailyService;
import com.finance.capacity.siteDetail.bean.pojo.SiteDetailList;
import com.finance.capacity.siteDetailLog.bean.pojo.SiteDetailLog;
import com.finance.capacity.siteDetailLog.capService.ISiteDetailLogService;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: gly
 * @Date: Created in 2017-05-23
 */
@Controller
@RequestMapping("/capacity/coefficientTrend")
public class CoefficientTrendController extends BaseController {

    @Resource
    private ISiteCoefficientDailyService siteCoefficientDailyService;
    @Resource
    private IDeliveryDetailService deliveryDetailService;
    @Resource
    private ISiteDetailLogService siteDetailLogService;

    @RequestMapping("/list")
    public Result getCoeTrendList(CoeTrendReq form){
        Page page = Page.getInstance(form);
        SiteCoeDailyList siteCoeDailyList = new SiteCoeDailyList();
        if( !"-1".equals(form.getSiteId()) ){
            siteCoeDailyList.setProvinceId("-1");
            siteCoeDailyList.setCityId("-1");
            siteCoeDailyList.setSiteId(form.getSiteId());
        }else if( !"-1".equals(form.getCityId()) ){
            siteCoeDailyList.setProvinceId("-1");
            siteCoeDailyList.setCityId(form.getCityId());
            siteCoeDailyList.setSiteId("-1");
        }else if( !"-1".equals(form.getProvinceId()) ){
            siteCoeDailyList.setProvinceId(form.getProvinceId());
            siteCoeDailyList.setCityId("-1");
            siteCoeDailyList.setSiteId("-1");
        }
        siteCoeDailyList.setBeginTime(form.getBeginTime());
        siteCoeDailyList.setEndTime(form.getEndTime());
        if( StringUtils.isNotBlank(form.getKeyWords()) ){
            List<String> keyWordsList = Arrays.asList(form.getKeyWords().split("、"));
            siteCoeDailyList.setKeyWords(keyWordsList);
        }
        page.setParams(siteCoeDailyList);

        PageResultBO<SiteCoeDaily> resultBO = siteCoefficientDailyService.coeTrendList(page);
        return getSuccessResult(resultBO);
    }


    @RequestMapping("/deliveryList")
    public Result getDeliveryList( CoeTrendReq form ){
        if(StringUtils.isBlank( form.getRelationId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<DeliveryDetailList> deliveryDetailLists = deliveryDetailService.getCoeDeliveryList(form.getRelationId());
        return getSuccessResult(deliveryDetailLists);
    }


    @RequestMapping("/siteLogList")
    public Result getSiteLogList( CoeTrendReq form ){
        if(StringUtils.isBlank( form.getRelationId() ) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<SiteDetailLog> siteDetailLogs = siteDetailLogService.getSiteLog(form.getRelationId());
        return getSuccessResult(siteDetailLogs);
    }



    @RequestMapping("/export")
    public Result exportMaintainList(CoeTrendReq form, HttpServletResponse response) throws UnsupportedEncodingException {

        if(StringUtils.isBlank( form.getSiteId() ) || StringUtils.isBlank(form.getBeginTime()) || StringUtils.isBlank(form.getEndTime()) ){
            return getFailResult(BaseConstants.ERR_PARAMS_NULL,BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }

        SiteCoeDailyList siteCoeDailyList = new SiteCoeDailyList();
        if( !"-1".equals(form.getSiteId()) ){
            siteCoeDailyList.setProvinceId("-1");
            siteCoeDailyList.setCityId("-1");
            siteCoeDailyList.setSiteId(form.getSiteId());
        }else if( !"-1".equals(form.getCityId()) ){
            siteCoeDailyList.setProvinceId("-1");
            siteCoeDailyList.setCityId(form.getCityId());
            siteCoeDailyList.setSiteId("-1");
        }else if( !"-1".equals(form.getProvinceId()) ){
            siteCoeDailyList.setProvinceId(form.getProvinceId());
            siteCoeDailyList.setCityId("-1");
            siteCoeDailyList.setSiteId("-1");
        }
        siteCoeDailyList.setBeginTime(form.getBeginTime());
        siteCoeDailyList.setEndTime(form.getEndTime());
        if( StringUtils.isNotBlank(form.getKeyWords()) ){
            List<String> keyWordsList = Arrays.asList(form.getKeyWords().split("、"));
            siteCoeDailyList.setKeyWords(keyWordsList);
        }

        List<SiteCoeDaily> exportList = siteCoefficientDailyService.exportList(siteCoeDailyList);
        if (exportList.size() > 0) {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "公平系数趋势列表_" + df.format(new Date()); // 文件名
            String lastStr = ".xls";// 文件名后缀
            fileName = fileName + lastStr;

            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet("公平系数趋势列表信息");
            sheet.createDrawingPatriarch();//
            HSSFRow row = sheet.createRow(0);
            String[] title = new String[]{"序号", "省公司", "市公司", "站点", "小件员数", "公平系数单量", "公平系数", "日期"};
            for (int i = 0; i < title.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }

            for (int i = 0; i < exportList.size(); i++) {
                SiteCoeDaily t = (SiteCoeDaily) exportList.get(i);
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(t.getProvinceName());
                row.createCell(2).setCellValue(t.getCityName());
                row.createCell(3).setCellValue(t.getSiteName());
                row.createCell(4).setCellValue(t.getWorkerNum());
                row.createCell(5).setCellValue(t.getOrderEfficientNum());
                row.createCell(6).setCellValue(String.valueOf(t.getCoefficient()));
                row.createCell(7).setCellValue(t.getSiteDate());
            }

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out;
            try {
                out = response.getOutputStream();
                workbook.write(out);
                out.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER) );
            }
            return null;
        } else {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL) );
        }
    }


}
